import axios from 'axios';
import { MessageBox } from 'element-ui';
import { Loading } from 'element-ui';
import router from '../router';
import store from '../store'

//同源验证策略
axios.defaults.withCredentials=false
//显示加载
let loading;
let loadingNum = 0;
function startLoading() {
    loading = Loading.service({
        lock: true,
        text: '努力请求中……',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
//关闭加载
function endLoading() {
    loading.close()
}

const service = axios.create({
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了，暂时不使用了
    // baseURL: 'https://www.easy-mock.com/mock/592501a391470c0ac1fab128',
    timeout: 5000
});

service.interceptors.request.use(
    config => {
        if(config.config.showLoading){
            startLoading();
            loadingNum++;
        }
        if(store.state.token){
            config.headers['token'] = store.state.token;
        }else{
            config.headers['token'] = localStorage.getItem('token');
            store.commit('setToken', localStorage.getItem('token'))
        }
        
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        if(loadingNum > 0){
            endLoading();
        }
        if(response.headers.token){
            localStorage.setItem('token', response.headers.token)
            store.commit('setToken', response.headers.token)
        }
        return response.data;
    },
    error => {
        if(loadingNum > 0){
            endLoading();
        }
        if (error.response.status === 403) {
            MessageBox.alert(error.response.data.msg, '登录超时',{
                confirmButtonText: '跳转登录页面',
                callback: action => {
                    router.push('/login')
                }
            })
        }else if(error.response.status === 401) {
            MessageBox.alert(error.response.data.msg, '无权限提示',{
                callback: action => {
                    router.back();
                }
            })
        }else{
            MessageBox.alert('服务器超时响应,请稍后尝试!','服务器异常')
        }
        return Promise.reject();
    }
);

export default service;
